﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ABMath.ModelFramework;

namespace ExtraControlLibrary.VisualControls
{
    public partial class ExtraFunctionPanel : UserControl
    {
        public class ExtraFunctionArgs : EventArgs
        {
            public int index;
            public object result;
        }
        public delegate void FunctionCompletedNotification(object sender, ExtraFunctionArgs args);
        public event FunctionCompletedNotification FunctionCompleted;

        private IExtraFunctionality functionObject;
        public IExtraFunctionality FunctionObject
        {
            get { return functionObject;  }
            set
            {
                functionObject = value;
                AssociateButtons();
            }
        }

        private Button[] buttonArray;

        private void AssociateButtons()
        {
            if (functionObject == null)
            {
                button1.Hide();
                button2.Hide();
                button3.Hide();
                return;
            }

            buttonArray = new[] { button1, button2, button3 };

            for (int i=0 ; i<buttonArray.Length ; ++i)
                if (functionObject.NumAuxiliaryFunctions() > i)
                {
                    buttonArray[i].Text = functionObject.AuxiliaryFunctionName(i);
                    buttonArray[i].Click += ButtonClicked;
                    var helpString = functionObject.AuxiliaryFunctionHelp(i);
                    if (!string.IsNullOrEmpty(helpString))
                    {
                        var toolTip = new ToolTip();
                        toolTip.SetToolTip(buttonArray[i], helpString);
                    }
                    buttonArray[i].Show();
                }
                else
                    buttonArray[i].Hide();
        }

        private void ButtonClicked(object sender, EventArgs e)
        {
            // work out index
            int idx = -1;
            for (int i=0 ; i<buttonArray.Length ; ++i)
                if (ReferenceEquals(sender, buttonArray[i]))
                    idx = i;
            if (idx != -1)
            {
                object output = null;
                functionObject.AuxiliaryFunction(idx, out output);
                if (FunctionCompleted != null)
                    FunctionCompleted(this, new ExtraFunctionArgs(){index=idx, result=output});
            }
        }

        public ExtraFunctionPanel()
        {
            InitializeComponent();
        }

        public ExtraFunctionPanel(IExtraFunctionality functionObject)
        {
            InitializeComponent();
            FunctionObject = functionObject;
        }
    }
}
